/**
  * Definition for a binary tree node.
  * public class TreeNode {
  *     int val;
  *     TreeNode left;
  *     TreeNode right;
  *     TreeNode(int x) { val = x; }
  * }
  */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return root;
        //p/q是root
        if(root==p||root==q) return root;

        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);

        //两边都找到了
        if(left != null && right != null) return root;
        //找到一边
        if(left == null && right != null) return right;
        if(right == null && left != null) return left;
        //两边都找不到
        return null;
    }
}